//
//  WMERootViewController.m
//  everyDay_duiTang
//
//  Created by 恩叔 on 16/1/15.
//  Copyright © 2016年 enshu. All rights reserved.
//

#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "WMERootViewController.h"
#import "WMEFirstPageModel.h"
#import "WMEFirstPageCollectionViewCell.h"
#import "WMELayout.h"
#import <Masonry.h>
#import <MJRefresh.h>
#import "WMEFirstPageInformationVC.h"
#import "WMEUserViewController.h"
#import "WMEAlbumViewController.h"
#import "WMEContentViewController.h"
#import "WMElunbotu.h"
@interface WMERootViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, WMELayoutItemHeightDelegate ,pushAlbumDelegate, pushYongHuDelegate>
@property (nonatomic, retain)NSMutableArray *dataArr;//数据数组
@property (nonatomic, retain)UICollectionView *collection;//主视图的collection
@property (nonatomic, copy)NSString *url_str;//网络请求的网址
@property (nonatomic, assign)NSInteger count;//给data数组中添加 数据 的个数
@property (nonatomic, retain)NSArray *luoboArr;
@property (nonatomic, retain)UICollectionView *headCollection;
@property (nonatomic, retain)UIView *lbView;

@end

@implementation WMERootViewController

- (void)dealloc
{
    [_dataArr release];
    [_collection release];
    [_url_str release];
    [_luoboArr release];
    [_headCollection release];
    [_lbView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"首页";
    
    //lunbotu
    [self lunbotuData];
    //视图collection
    [self chuangjianView];
    //数据处理
    [self data];
    //下拉刷新
    [self refreshFunction];
    //上拉加载
    self.count = 0;
    [self loadingFunction];
}
- (void) chuangjianView
{
    //自定义layout
    WMELayout *layout = [[WMELayout alloc] init];
    //layout的count为2 两列
    layout.columCount = 2;
    //layout 的 列间距
    layout.columSparce = 10;
    //layout 的 行间距
    layout.rowSparce = 10;
    //layout的边距
    layout.edgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
   
    
    //初始化 collection
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49) collectionViewLayout:layout];
//    [layout release];
    //设置collection的背景颜色
    _collection.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
    //签协议
    layout.delegate = self;
    _collection.dataSource = self;
    _collection.delegate = self;
    
    _collection.contentInset = UIEdgeInsetsMake(235 * WIDTH / 414, 0, 0, 0);
    self.lbView = [[UIView alloc] initWithFrame:CGRectMake(0, -235 * WIDTH / 414, WIDTH, 235 * WIDTH / 414)];
    [self.collection addSubview:_lbView];
    //把collection添加进视图
    [self.view addSubview:_collection];
    
    //未测试
#warning 首页的collectionView 我不会使用 masonry  有 bug 待研究
//    __block __typeof(&*self)ws = self;
//    [_collection mas_makeConstraints:^(MASConstraintMaker *make) {
////        make.edges.equalTo(ws.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
//        make.left.equalTo(ws.view).with.offset(0);
//        make.right.equalTo(ws.view).with.offset(0);
//        make.top.equalTo(ws.view).with.offset(0);
//        make.bottom.equalTo(ws.view).with.offset(0);
//    }];
    
    [layout release];
    [_collection release];
}


#pragma mark -点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
//    NSLog(@"indexPath:%ld", (long)indexPath.row);
    //创建 对象
    WMEFirstPageInformationVC *information = [[WMEFirstPageInformationVC alloc] init];
    
    WMEFirstPageModel *m = _dataArr[indexPath.item];
    //把ID 传递给 下一页 的 接口
    information.jiekou = m.ID.stringValue;
    [self.navigationController pushViewController:information animated:YES];
    [information release];
}

//行数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    //collection的里 cell 的个数
    return _dataArr.count;
}
//cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView registerClass:[WMEFirstPageCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    WMEFirstPageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (_dataArr.count != 0) {
        //注册重用池 为cell
        //创建cell
        //创建model
        WMEFirstPageModel *m = _dataArr[indexPath.item];
        //把 model 传递给 cell
        cell.model = m;
        cell.delegate = self;
        cell.albumDelegate = self;
    }
    return cell;
}
- (CGFloat)layout:(WMELayout *)layout heightForItemAtIndexPath:(NSIndexPath *)indexPath width:(CGFloat)width
{
    if (_dataArr.count != 0) {
        //计算图片的高度
        //tw/th = iw/ih
        WMEFirstPageModel *m = _dataArr[indexPath.item];
        //图片高度
        CGFloat imgH = width * m.height.doubleValue / m.width.doubleValue;
        //文字高度
        //    NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
        //    // 预设尺寸 文本最大不超过这个尺寸
        //    // 根据设置的宽度计算高度(宽度和label保持一致)
        //    CGSize size = CGSizeMake((414 - 30) /2, 1000);
        //    // 根据文本 计算出一个CGRect
        //    // 参数1: 尺寸范围
        //    // 参数2: 文本属性
        //    // 参数3: 按照什么方式获取rect
        //    // 参数4: nil
        //    CGRect rect = [m.msg boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        //    CGFloat h3 = rect.size.height;
        
        //文本高度
        CGFloat textHeight = [WMEFirstPageCollectionViewCell heightWithText:m.msg];
        //判断文本框 高度是否 超过 15.51 * 6 的 高度(6行的高度)
        if (textHeight >= 15.51 * 6) {
            //设置最大文本框行数 为 6行;
            textHeight = 15.51 * 6;
        }
        //    NSLog(@"%@      ======     %f  ~~~~ %f", m.msg, imgH, textHeight);
        // 每个cell的高度 由 图片高度 和 文本高度  + 其他控件高度(80)
        return imgH + textHeight + 80;
    }
    return 0;
}


//数据请求
- (void)data
{
    self.url_str = @"http://www.duitang.com/napi/index/hot/?__dtac=%257B%2522_r%2522%253A%2520%2522847847%2522%257D&app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=iPhone%205&device_platform=iPhone5%2C2&include_fields=sender%2Cfavroite_count%2Calbum%2Cicon_url%2Creply_count%2Clike_count&limit=0&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=568&screen_width=320&start=0";
    //AFN网络请求
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    [data GET:_url_str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        NSArray *arr = responseObject[@"data"][@"object_list"];
        _count += 24;
        self.dataArr = [WMEFirstPageModel modelHandlerWithArray:arr];
        [_collection reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
}
#pragma mark - 轮播图数据
- (void)lunbotuData
{
    NSString *str = @"http://www.duitang.com/napi/ad/banner/week/?__dtac=%257B%2522_r%2522%253A%2520%2522574004%2522%257D&app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=iPhone%205&device_platform=iPhone5%2C2&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=568&screen_width=320";
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    [data GET:str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        
        NSArray *arr = responseObject[@"data"];
        self.luoboArr = [WMEFirstPageModel modelHandlerWithArray:arr];
        NSMutableArray *lbArr = [NSMutableArray array];
        NSMutableArray *labelArr = [NSMutableArray array];
        NSMutableArray *sjArr = [NSMutableArray array];
        for (NSInteger i = 0; i<_luoboArr.count; i++) {
            WMEFirstPageModel *m = _luoboArr[i];
            NSString *k = m.image_url;
            NSString *l = m.descriptions;
            NSString *s = m.enabled_at_str;
            [lbArr addObject:k];
            [labelArr addObject:l];
            [sjArr addObject:s];
            //            NSLog(@"~~%@", m.image_url);
        }
        
        WMElunbotu *img = [[WMElunbotu alloc] initWithFrame:CGRectMake(0, 0, WIDTH , 235 * WIDTH / 414) URLArr:lbArr timeInterval:2 Yuandianframe:CGRectMake(0, 200 * WIDTH /414, 235 *WIDTH / 414, 30) LabelArr:labelArr Shijian:sjArr];
        img.lbArr = _luoboArr;
        [self.lbView addSubview:img];
        
        [img release];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];

}

#pragma mark -刷新
- (void)refreshFunction
{
    self.collection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self.dataArr removeAllObjects];
        [self data];
        [self.collection.mj_header endRefreshing];
    }];
}
#pragma maek - 加载
- (void)loadingFunction
{
    self.collection.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSString *url = [_url_str stringByReplacingOccurrencesOfString:@"start=0" withString:[NSString stringWithFormat:@"start=%ld", _count]];
        //AFN网络请求
        AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
        [data GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //        NSLog(@"%@", responseObject);
            NSArray *arr = responseObject[@"data"][@"object_list"];
            _count += 24;
            // 把新请求来的数据 添加进 dataArr 数组
            NSArray *temp = [WMEFirstPageModel modelHandlerWithArray:arr];
            [_dataArr addObjectsFromArray:temp];
            [_collection reloadData];
            [_collection.mj_footer endRefreshing];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            nil;
        }];
    }];
}

#pragma mark - push用户界面(协议方法)
- (void)pushYongHu:(NSString *)str
{
    NSString *userTemp = @"http://www.duitang.com/napi/people/profile/?__dtac=%257B%2522_r%2522%253A%2520%2522998121%2522%257D&_ts=1452865118.002704&app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=iPhone%205&device_platform=iPhone5%2C2&include_fields=relationship%2Cbind_status%2Cinterests%2Cidentity%2Ccity%2Ccitycode%2Cgender%2Cbirthday%2Crecommend_info%2Cclub_count&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=568&screen_width=320&user_id=11200118";
    NSString *userStr = [userTemp stringByReplacingOccurrencesOfString:@"11200118" withString:str];
    //AFN网络请求
    AFHTTPSessionManager *userData = [AFHTTPSessionManager manager];
    [userData GET:userStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@", responseObject);
        NSMutableDictionary *dic = responseObject[@"data"];
        WMEUserViewController *userVC = [[WMEUserViewController alloc] init];
        UINavigationController *userNavi = [[UINavigationController alloc] initWithRootViewController:userVC];
        userVC.userId = str;
        userVC.userDic = dic;
        [self presentViewController:userNavi animated:YES completion:^{
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
    

}

#pragma mark - push专辑页 (协议方法)
- (void)pushAlbum:(NSString *)str maxCount:(NSNumber *)count
{
    //AFN网络请求
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    NSString *temp = @"http://www.duitang.com/napi/album/detail/?__dtac=%257B%2522_r%2522%253A%2520%2522616818%2522%257D&album_id=77153908&app_code=gandalf&app_version=5.9%20rv%3A150681&device_name=Unknown%20iPhone&device_platform=iPhone7%2C2&include_fields=id%2Cname%2Cdesc%2Cuser%2Clike_count%2Clike_id%2Ccount%2Ccovers%2Cmanagers%2Cmembers%2Cmember_count%2Ccategory%2Cshare_links_2&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=667&screen_width=375&user_id=0";
    NSString *urlStr = [temp stringByReplacingOccurrencesOfString:@"album_id=77153908" withString:[NSString stringWithFormat:@"album_id=%@",str]];
    [data GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@", responseObject);
        NSMutableDictionary *dic = responseObject[@"data"];
        WMEContentViewController *contentView = [[WMEContentViewController alloc] init];
        contentView.albumDic = dic;

        [self.navigationController pushViewController:contentView animated:YES];
        [contentView release];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
